package com.yhh;

import com.yhh.Entity.Command;
import com.yhh.Entity.HandlerCommand;
import com.yhh.Exceptions.InstructionException;
import com.yhh.Exceptions.NonInstructionException;

import java.net.Socket;
import java.util.Map;

import static com.yhh.Pipeline.pipeline;

public class ClearCommand extends Command implements HandlerCommand {
    private static final String c = "clear";

    protected ClearCommand(Socket socket) {
        super(socket);
        command.add("-m");
        command.add("-a");
    }

    @Override
    public void handlerParameter(Map<String, String> args) throws InstructionException, NonInstructionException {
        if (args.get("-m") != null) {
            String m = args.get("-m");
            if (m.length() != 10 || pipeline.get(m) == null) throw new InstructionException("-m参数有误", c);
        }
    }

    @Override
    public boolean check(Map<String, String> args) throws NonInstructionException, InstructionException {
        checkParameter(args);
        handlerParameter(args);
        return true;
    }

    @Override
    public void handlerCommand(Map<String, String> args){
        handlerClear(args);
        ServerThread.save();
    }

    //处理清除指令
    private void handlerClear(Map<String, String> args){
        if (args.get("-m") != null) {
            //移除-m参数
            pipeline.remove(args.get("-m"));
        } else if (args.get("-a") != null) {
            pipeline.forEach((key, file) -> {
                if (file.getIp().equals(socket.getInetAddress().toString())) {
                    pipeline.remove(key);
                }
            });
        } else {
            //全部删除过期的
            pipeline.forEach((key, file) -> {
                System.out.println("key" + key);
                if (file.getIp().equals(socket.getInetAddress().toString()) && (file.getCounts() <= 0 || file.isExpired())) {
                    pipeline.remove(key);
                }
            });
        }
        sendMsg("success");
    }
}
